package core.database.service.impl;


import core.config.exception.CloudException;
import core.database.pojo.constant.SqlType;
import core.database.pojo.entity.IConnection;
import core.database.service.DataBaseService;
import core.database.pojo.entity.DataBase;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * @author Long
 * @version 1.0
 * @description:
 * @title DataBaseServiceImpl
 * @date 2021/3/6 9:29
 */
public class DataBaseServiceImpl implements DataBaseService {
    @Override
    public IConnection getCon(DataBase db) {
        String driver;
        String url;
        switch (db.getType().toUpperCase()) {
            case SqlType.MYSQL:
                driver = SqlType.MYSQL_DRIVER;
                url = SqlType.MYSQL_URL.replace("[ip]", db.getIp()).replace("[port]", "3306").replace("[library]", db.getLibrary());
                break;
            case SqlType.SQLSERVER:
                driver = SqlType.SQLSERVER_DRIVER;
                url = SqlType.SQL_SERVER_URL.replace("[ip]", db.getIp()).replace("[port]", "1433").replace("[library]", db.getLibrary());
                break;
            //TODO 增加数据库选择
            default:
                return null;
        }
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            throw new CloudException("驱动加载失败");
        }
        try {
            Properties props = new Properties() {{
                this.put("remarksReporting", "true");
                this.put("user", db.getUser());
                this.put("password", db.getPassword());
            }};
            return new IConnection(DriverManager.getConnection(url, props));
        } catch (SQLException e) {
            throw new CloudException("数据库连接失败");
        }
    }

    @Override
    public DatabaseMetaData getMataData(IConnection con) {
        try {
            return con.getCon().getMetaData();
        } catch (SQLException throwables) {
            throw new CloudException("驱动加载失败");
        }
    }

    @Override
    public List<String> getSchemas(DatabaseMetaData metaData) {
        try {
            ResultSet resultSet = metaData.getCatalogs();
            return new ArrayList<>() {{
                while (resultSet.next()) {
                    this.add(resultSet.getString(1));
                }
            }};
        } catch (SQLException throwables) {
            throw new CloudException("数据库列表获取失败");
        }
    }
}
